package com.zxx.flowerstore.utils.common;

import com.zxx.flowerstore.dao.FlowerCodeRuleMapper;
import com.zxx.flowerstore.entity.FlowerCodeRule;
import com.zxx.flowerstore.entity.constant.MagicConstant;
import com.zxx.flowerstore.entity.enums.ResultEnum;
import com.zxx.flowerstore.utils.utils.EmptyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName GeneratorCodeForMysql
 * @Author Admin
 * @Date 2021/3/15 22:11
 * @Description GeneratorCodeForMysql
 * @Version 1.0
 */
@Component
public class GeneratorCodeForMysql {
    @Autowired
    private FlowerCodeRuleMapper codeRuleDao;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 通用code生成方法
     *
     * @param codeRule
     * @return
     */
    public String GeneratorCode(FlowerCodeRule codeRule) {

        //判断是否传入生成规则
        if(EmptyUtil.isEmpty(codeRule)){
            throw new MyException(ResultEnum.ERROR.getCode(), "未传入代码生成规则！");
        }

        //判断是否传入规则名
        if(EmptyUtil.isEmpty(codeRule.getSeqTypeId())){
            throw new MyException(ResultEnum.ERROR.getCode(), "未传入代码生成规则名！");
        }

        //判断有没有传入生成序号数量
        if(EmptyUtil.isEmpty(codeRule.getSize())){
            codeRule.setSize(1);    //如果没传 默认为生成1个
        }

        //判断有没有传入规则ID
        if(EmptyUtil.isEmpty(codeRule.getPlatId())){
            codeRule.setPlatId("");     //给默认值1
        }

        //获取code
        codeRuleDao.getCode(codeRule);

        //判断是否生成成功
        if (StringUtils.isEmpty(codeRule.getCode()) || MagicConstant.ZERO == codeRule.getIndex()) {
            throw new MyException(ResultEnum.ERROR.getCode(), "代码生成失败了 😶！");
        }

        if (codeRule.getSize() > MagicConstant.ONE) {
            //处理code
            List<String> codeList = new ArrayList<>();
            int seq = Integer.parseInt(codeRule.getCode().substring(codeRule.getCode().length() - codeRule.getIndex(), codeRule.getCode().length()));
//            String prefix=codeRule.getCode().replace(seq+"","");
            String prefix = codeRule.getCode().substring(MagicConstant.ZERO, codeRule.getCode().length() - codeRule.getIndex());
            for (int i = 0; i < codeRule.getSize(); i++) {

                StringBuffer codeTemp = new StringBuffer(prefix);

                String str = (seq + i) + "";
                for (int x = str.length(); x < codeRule.getIndex(); x++) {
                    codeTemp.append("0");
                }
                codeList.add(codeTemp.toString() + (seq + i));
            }

            return String.join(",", codeList);


        } else {
            return codeRule.getCode();
        }


    }

}
